
package com.rt.schedulenew.utils.checkparam.config;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSONObject;
import com.rt.schedulenew.utils.checkparam.common.BaseUtil;
import org.aspectj.lang.annotation.Around;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import org.springframework.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@Component
public class CheckRegexParamAspect
{
    @Pointcut("execution(public * com.rt..*Controller.*(..)) || execution(public * com.rt.schedulenew.*Controller.*(..)) || execution(public * com.rt..*Api.*(..))")
    public void checkNull() {
    }
    
    @Around("checkNull()")
    public Object check(ProceedingJoinPoint point) throws Throwable {
        String msg = this.doCheck(point);
        if (!StringUtils.isEmpty(msg)) {
            return JsonResultUtil.failure(msg);
        }
        Object obj = point.proceed();
        return obj;
    }
    
    private String doCheck(ProceedingJoinPoint point) {
        Object[] arguments = point.getArgs();
        Method method = BaseUtil.getMethod(point);
        String methodInfo = StringUtils.isEmpty(method.getName()) ? "" : ("  方法名 " + method.getName());
        String msg = "";
        if (BaseUtil.isCheck(method, arguments, CheckRegex.class)) {
            CheckRegex annotation = method.getAnnotation(CheckRegex.class);
            String[] fields = annotation.value();
            Object vo = arguments[0];
            if (vo == null) {
                msg = "param can not be null";
            }
            else {
                for (String field : fields) {
                    try {
                        String fieldstr = "";
                        String pattern = "";
                        if (field.contains(":")) {
                            pattern = field.split(":")[1];
                            fieldstr = field.split(":")[0];
                        }
                        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(vo));
                        if (!StringUtils.isEmpty((Object)jsonObject.getString(fieldstr))) {
                            boolean isMatch = Pattern.matches(pattern, jsonObject.getString(fieldstr));
                            if (!isMatch) {
                                msg = msg + fieldstr + "校验不通过，";
                            }
                        }
                    }
                    catch (Exception e) {
                        return "参数解析异常,请使用标准json格式";
                    }
                }
                if (!StringUtils.isEmpty((Object)msg)) {
                    msg = msg.substring(0, msg.length() - 1) + "";
                }
            }
        }
        return msg;
    }
}
